<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>通信-数据通道</h1>
    <button>发送数据</button>

    <script>
        let port
        let count = 0
        window.onmessage = (event) => {
            if (event.data === '__init_port__') {
                // 获取到另一个端口
                port = event.ports[0]
                // 可以在网页侧注册事件监听，接收应用侧发送的数据
                port.onmessage = (event) => {
                    console.log('网页中接收到的数据:', event.data)
                }
            }
        }
        document.querySelector('button').onclick = () => {
            port.postMessage('页面计数:' + (++count))
        }
    </script>
</body>
</html>